package jp.sinya;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 防盗链
 * 使用 Referer 识别
 * 如果不是通过本站的超链接发出的，就可以拦截发送错误状态码404 或者是其它处理
 */
public class DemoServlet9 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-Type", "text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<h3>request ok</h3><br/>");

        String referer = req.getHeader("Referer");

        //如果是直接访问这个servlet，不包含localhost的主机名，就会被跳到百度
        if (referer == null || !referer.contains("localhost")) {
            resp.sendRedirect("http://www.baidu.com");

            //如果是通过本站的test1.html来点击进入，就会执行下面的内容
        } else {
            writer.write("<p>serverPort: " + referer + "</p><br/>");
            writer.write("<p>Hello</p><br/>");
        }

        resp.setStatus(200);
    }
}
